package com.yl.chainStore.services.impl.warehouse

import com.yl.chainStore.common.LockObjects
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.warehouse.WarehouseProfitLossOrder
import com.yl.chainStore.entity.warehouse.WarehouseProfitLossOrderDetail
import com.yl.chainStore.mapper.warehouse.WarehouseProfitLossOrderDetailMapper
import com.yl.chainStore.mapper.warehouse.WarehouseProfitLossOrderMapper
import com.yl.chainStore.pojo.vo.warehouse.OutBatchCountVo
import com.yl.chainStore.pojo.vo.warehouse.UpdateWarehouseGoodVo
import com.yl.chainStore.services.warehouse.IWarehouseProfitLossOrderService
import com.yl.chainStore.services.warehouse.IWarehouseService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
class WarehouseProfitLossOrderServiceImpl(
	private val warehouseProfitLossOrderMapper: WarehouseProfitLossOrderMapper,
	private val warehouseProfitLossOrderDetailMapper: WarehouseProfitLossOrderDetailMapper
) : IWarehouseProfitLossOrderService {
	companion object {
		private val log = LoggerFactory.getLogger(IWarehouseProfitLossOrderService::class.java)
	}

	@Autowired
	lateinit var iCompanyDeptService: ICompanyDeptService

	@Autowired
	lateinit var iWarehouseService: IWarehouseService

	@Autowired
	lateinit var iCompanyUserService: ICompanyUserService

	override fun getOrder(orderId: Long): WarehouseProfitLossOrder? {
		log.info("损益单 ==> 获取订单基本数据 orderId{}", orderId)
		val order = warehouseProfitLossOrderMapper.selectById(orderId) ?: return null
		val dept = iCompanyDeptService.getDept(order.deptId)
		if (dept != null) {
			order.deptName = dept.name
		}
		val orderUser = iCompanyUserService.getUser(order.orderUserId)
		if (orderUser != null) {
			order.orderUserName = orderUser.realName
		}
		return order
	}

	override fun addDetail(detail: WarehouseProfitLossOrderDetail): ResponseBody {
		log.info("损益单  ==> 添加明细 detail:{}", detail)
		warehouseProfitLossOrderDetailMapper.insert(detail)
		return returnSuccess()
	}

	override fun getOrderDetail(orderId: Long): List<WarehouseProfitLossOrderDetail> {
		log.info("损益单  ==> 获取明细 orderId:{}", orderId)
		return warehouseProfitLossOrderDetailMapper.getListByOrderId(orderId)
	}

	override fun completeOrder(orderId: Long): ResponseBody {
		log.info("损益单  ==> 审核通过 orderId:{}", orderId)
		val order = warehouseProfitLossOrderMapper.selectById(orderId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到该订单，请刷新重试"
		)
		if (order.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		order.status = Status.COMPLETE
		order.dealUserId = getContext().userId
		order.dealTime = Date()
		warehouseProfitLossOrderMapper.updateById(order)
		order.details = getOrderDetail(orderId)
		val str: String = order.companyId.toString() + "_" + order.deptId.toString()
		synchronized(LockObjects.getWarehouseLock(str)) {
			var i = 1
			for (detail in order.details!!) {
				log.info("损益单 ==> 仓库数据调动 ：detail{}", detail)
				detail.status = Status.COMPLETE
				if (detail.goodCount == 0) {
					return returnError(
						ErrorCode.DATA_IS_NOT_FIND,
						"请输入第" + i + "行物品损益数量"
					)
				}
				//仓库数据处理
				if (detail.goodCount>0) {
					//入
					if (detail.batchCountId != null) {
						//有批次的获取批次价格
						val batchCount =
							iWarehouseService.getGoodBatchCount(detail.batchCountId!!) ?: return returnError(
								ErrorCode.DATA_IS_NOT_FIND,
								"仓库未找到第" + i + "行批次物品"
							)
						detail.price = batchCount.goodPrice
					} else {
						//没批次的，获取最后一次入库的批次和单价
						val batchCount =
							iWarehouseService.getLastBatchCount(order.companyId, order.deptId, detail.itemId)
								?: return returnError(
									ErrorCode.DATA_IS_NOT_FIND,
									"仓库未找到第" + i + "行物品"
								)
						detail.batchCountId = batchCount.id
						detail.price = batchCount.goodPrice
					}
					//组装入库记录 然后入库
					val log = UpdateWarehouseGoodVo(
						associatedType = TypeEnum.WAREHOUSE_LOG_TYPE_PROFIT_LOSS_PROFIT,
						associatedId = order.id,
						remark = detail.remark,
						deptId = order.deptId,
						companyId = order.companyId,
						itemId = detail.itemId,
						goodCount = detail.goodCount,
						unitPrice = detail.price,
						detailId = detail.id
					)
					val inWarehouse = iWarehouseService.inWarehouse(detail.batchCountId, log)
					if (inWarehouse.code != ErrorCode.SUCCESS.code) {
						return inWarehouse
					}
					warehouseProfitLossOrderDetailMapper.updateById(detail)
				} else {
					//出
					val log = UpdateWarehouseGoodVo(
						associatedType = TypeEnum.WAREHOUSE_LOG_TYPE_PROFIT_LOSS_LOSS,
						associatedId = order.id,
						remark = detail.remark,
						deptId = order.deptId,
						companyId = order.companyId,
						itemId = detail.itemId,
						goodCount = -detail.goodCount,
						unitPrice = detail.price,
						detailId = detail.id
					)
					val res = iWarehouseService.outWarehouse(detail.batchCountId, log)
					if (res.code != ErrorCode.SUCCESS.code) {
						return res
					}
					val resList = res.data as List<*>
					warehouseProfitLossOrderDetailMapper.deleteById(detail.id)
					for(vo in resList){
						vo as OutBatchCountVo
						detail.id = 0
						detail.goodCount = vo.count
						detail.batchCountId = vo.id
						detail.price = vo.price
						warehouseProfitLossOrderDetailMapper.insert(detail)
					}
				}
				i++
			}
		}
		return returnSuccess()
	}

	override fun noPassOrder(orderId: Long): ResponseBody {
		log.info("损益单  ==> 审核不通过 orderId:{}", orderId)
		val order = warehouseProfitLossOrderMapper.selectById(orderId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到该订单，请刷新重试"
		)
		if (order.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		order.status = Status.NO_PASS
		val details = getOrderDetail(orderId)
		for (detail in details) {
			detail.status = Status.NO_PASS
			warehouseProfitLossOrderDetailMapper.updateById(detail)
		}
		warehouseProfitLossOrderMapper.updateById(order)
		return returnSuccess()
	}

	override fun cancelOrder(orderId: Long): ResponseBody {
		log.info("损益单  ==> 取消,作废 orderId:{}", orderId)
		val order = warehouseProfitLossOrderMapper.selectById(orderId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到该订单，请刷新重试"
		)
		if (order.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		order.status = Status.SCRAP
		val details = getOrderDetail(orderId)
		for (detail in details) {
			detail.status = Status.SCRAP
			warehouseProfitLossOrderDetailMapper.updateById(detail)
		}
		warehouseProfitLossOrderMapper.updateById(order)
		return returnSuccess()
	}

	override fun delOrder(orderId: Long): ResponseBody {
		log.info("损益单  ==> 物理删除 orderId:{}", orderId)
		warehouseProfitLossOrderMapper.deleteById(orderId)
		return returnSuccess()
	}
}
